
import { useState, useLayoutEffect } from 'react';
import { Navigate } from 'react-router-dom';
import { useRequest } from "ahooks"
import {authorize, authToken} from "@/api/auth/auth";
import { AuthTokenVo} from "@/api/auth/type"

const AuthEntry = () => {
    const urlPath:string = window.location.pathname + window.location.search
    const [toPath, setToPath] = useState(urlPath)

    // 获取链接参数
    let urlId = ''
    const searchParams = new URLSearchParams(window.location.search);

    if(localStorage.getItem('urlId') && localStorage.getItem('urlId')!='null'){
        urlId= localStorage.getItem('urlId') as string
    }else{
        urlId= searchParams.get('id') as string
        urlId && localStorage.setItem('urlId', urlId)
    }
    const authorizeCode = searchParams.get('code') as string;
    
    // 获取code
    const authorizeReq = useRequest(authorize , {
        defaultParams:[urlId],
        manual: true,
        onSuccess:(result, params) => {
           const {model} = result.data


           setToPath(toPath => toPath = '/home')

        //    if(!authorizeCode){
        //     // 如果没有code , 跳转企微链接获取code
        //     window.location.href = model
        //    }else{
        //     // 如果有code , 获取token
        //     authTokenReq.run({code:authorizeCode , id:urlId } as AuthTokenVo)
        //    }
        }
    })

    // 获取token
    const authTokenReq = useRequest(authToken,{
        defaultParams:[{code:authorizeCode , id:urlId } as AuthTokenVo],
        manual: true,
        onSuccess:(result) => {
            const {token, type, businessType, chainShopId} = result.data.model
            localStorage.setItem('userToken',token)
            localStorage.setItem('userType',type)
            localStorage.setItem('businessType',businessType)
            localStorage.setItem('chainShopId',chainShopId)

            const navigatePath = '/home'
            setToPath(toPath => toPath = navigatePath)
         }
    })

    useLayoutEffect(() => {
        const isUserLoggedIn = localStorage.getItem('userToken'); // 假设用户登录状态存储在localStorage
        if(!isUserLoggedIn){
           authorizeReq.run(urlId)
        }else{
            // const userType = Number(localStorage.getItem('userType'))
            // const navigatePath = userType === 1 ? '/cockpit' : '/chainStat'
            const navigatePath = '/home'
            setToPath(toPath => toPath = navigatePath)
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [toPath])

    return (<Navigate to={toPath} replace />)
}

export default AuthEntry